package com.qf.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;

/**
 * @Description: 公用常量
 * @Data: 2022/9/2 0:56
 * @Pacakge: com.qf.config
 * @ClassName: SpringConfig
 * @Author: fan
 */
@Configuration//声明此类为配置类
@ComponentScan(basePackages = "com.qf")//扫描文件
@PropertySource("classpath:jdbc.properties")
@EnableTransactionManagement//开启事务管理
public class SpringConfig {
    @Value("${driverClassName}")
    private String driverClassName;
    @Value("${jdbcUrl}")
    private String jdbcUrl;
    @Value("${user}")
    private String user;
    @Value("${password}")
    private String password;

    @Bean("jdbcTemplate")
    public JdbcTemplate getJdbcTemplate(){
        return new JdbcTemplate(getDataSource());
    }
    @Bean("dataSource")
    public DataSource getDataSource(){
        DataSource dataSource = new DriverManagerDataSource();
        ((DriverManagerDataSource)dataSource).setDriverClassName(driverClassName);
        ((DriverManagerDataSource)dataSource).setUrl(jdbcUrl);
        ((DriverManagerDataSource)dataSource).setUsername(user);
        ((DriverManagerDataSource)dataSource).setPassword(password);
        return dataSource;
    }
    @Bean("transactionManager")
    public DataSourceTransactionManager getTransactionManager(){
        return new DataSourceTransactionManager(getDataSource());
    }
}

